import 'package:flutter/material.dart';
import 'package:p_location/home/constant/home_http_url.dart';
import 'package:p_location/home/obj/alarm_type_num.dart';
import 'package:p_location/home/obj/event/count_event.dart';
import 'package:p_location/home/obj/home_alarm_info_detail.dart';
import 'package:p_location/home/obj/obj_alarm_info.dart';
import 'package:p_location/home/res/res_home_alarm_info.dart';
import 'dart:math';

import 'package:p_location/home/widget/home_tab_alarm_card_widget.dart';
import 'package:p_location/home/widget/home_tab_count_widget.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:event_bus/event_bus.dart';

GlobalKey<_HomeTabAlarmWidgetState> alarmInfoKey = GlobalKey();

class HomeTabAlarmWidget extends StatefulWidget {
  @override
  _HomeTabAlarmWidgetState createState() => _HomeTabAlarmWidgetState();

  HomeTabAlarmWidget({Key key}) : super(key: key);
}

class _HomeTabAlarmWidgetState extends State<HomeTabAlarmWidget> {
  final double leftRadius = 3;
  final double rightRadius = 15;

  bool isRequesting = false;
  bool isLoading = true;
  int currentIndex = 0;

  final double cardMargin = 10;
  final double barItemMarginLeft = 15;
  final double barItemMarginRight = 15;

  double singleBarWidth = 0;

  HomeAlarmInfoDetail _homeAlarmInfoDetail;
  List<AlarmTypeNum> typeNumList = [];
  List<ObjAlarmInfo> list = [];

  EventBus eventBus = EventBus();

  @override
  void initState() {
    super.initState();
    eventBus.on<CountEvent>().listen((event) {
      print(event);
    });
//    getAlarmInfo();
    print("对数运算");
    print(log(9));
  }

  @override
  Widget build(BuildContext context) {
    return isLoading
        ? _loadingView
        : Container(
            margin: EdgeInsets.only(bottom: 10),
            child: Column(
              children: [
                HomeTabCountWidget(_homeAlarmInfoDetail?.alarmAllCount ?? 0),
                Offstage(
                  offstage: (_homeAlarmInfoDetail?.alarmAllCount ?? 0) == 0,
                  child: Card(
                    margin: EdgeInsets.all(cardMargin),
                    child: Column(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(6))),
                          child: Flex(
                            direction: Axis.horizontal,
                            children: [
                              _getTabItem(0, "区域人员报警"),
                              _getTabItem(1, "车辆报警"),
                              _getTabItem(2, "作业报警")

                            ],
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(6))),
                          child: Flex(
                            direction: Axis.horizontal,
                            children: [
                              _getTabLineItem(0),
                              _getTabLineItem(1),
                              _getTabLineItem(2),
                            ],
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(
                              barItemMarginLeft, 0, barItemMarginRight, 0),
                          padding: EdgeInsets.only(bottom: 15),
                          child: ListView.builder(
                              shrinkWrap: true,
                              //解决无限高度问题
                              physics: NeverScrollableScrollPhysics(),
                              itemCount: typeNumList?.length ?? 0,
                              itemBuilder: (context, index) {
                                return _getBarItem(
                                    typeNumList[index].alarmTypeName,
                                    typeNumList[index].num);
                              }),
                        ),
                      ],
                    ),
                  ),
                ),
                Offstage(
                    offstage: (_homeAlarmInfoDetail?.alarmAllCount ?? 0) == 0,
                    child: HomeTabAlarmCardWidget(
                        currentIndex, _getTabTotalCount(), list))
              ],
            ),
          );
  }

  _getTabTotalCount() {
    if (currentIndex == 0) {
      return _homeAlarmInfoDetail?.areaAlarmAllCount ?? 0;
    }
    if (currentIndex == 1) {
      return _homeAlarmInfoDetail?.vehicleAlarmAllCount ?? 0;
    }
    if (currentIndex == 2) {
      return _homeAlarmInfoDetail?.jobAlarmAllCount ?? 0;
    }
    return 0;
  }

  _getTabTotalCount2(index) {
    int candidate = 0;
    if (index == 0) {
      candidate = _homeAlarmInfoDetail?.areaAlarmAllCount ?? 0;
    }
    if (index == 1) {
      candidate = _homeAlarmInfoDetail?.vehicleAlarmAllCount ?? 0;
    }
    if (index == 2) {
      candidate = _homeAlarmInfoDetail?.jobAlarmAllCount ?? 0;
    }
    if (candidate > 99) {
      return "99+";
    }
    return '$candidate';
  }

  get _loadingView => Center(
        child: CircularProgressIndicator(),
      );

  _getTabItem(index, itemName) {
    return Expanded(
      flex: 1,
      child: GestureDetector(
        onTap: () {
          _pageSelect(index);
        },
        child: Stack(
          children: [
            Container(
              decoration: BoxDecoration(),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(itemName,
                      style: TextStyle(
                          fontSize: 15,
                          color: currentIndex == index
                              ? Color.fromARGB(255, 26, 103, 250)
                              : Colors.black))
                ],
              ),
              alignment: Alignment.center,
              height: 40,
//        color: Colors.red,
            ),
            Positioned(
                right: 2,
                top: 2,
                child: Offstage(
                  offstage: _getTabTotalCount2(index) == '0',
                  child: Container(
                    width: 15,
                    height: 15,
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(left: 3),
//                  padding: EdgeInsets.all(3),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(115)),
                        color: Colors.red),
                    child: Text(
                      '${_getTabTotalCount2(index)}',
                      style: TextStyle(color: Colors.white, fontSize: 7),
                    ),
                  ),
                ))
          ],
        ),
      ),
    );
  }

  _getTabLineItem(index) {
    return Expanded(
        child: Offstage(
      offstage: currentIndex != index,
      child: Container(
//      margin: EdgeInsets.only(left: 8, right: 8),
        height: 2,
        child: Text(""),
        color: Colors.blue,
      ),
    ));
  }

  _pageSelect(index) {
    if (currentIndex == index) {
      return;
    }
    setState(() {
      currentIndex = index;
      isLoading = true;
    });
    requestAlarmInfo();
  }

  requestAlarmInfo() {
    isRequesting = false;
    if (currentIndex == 0) {
      getAlarmInfo();
    } else if (currentIndex == 1) {
      getVehicleAlarmInfo();
    } else if (currentIndex == 2) {
      getJobAlarmInfo();
    }
  }

  _getBarItem(typeName, count) {
    return Container(
      alignment: Alignment.centerLeft,
      child: Container(
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(top: 10),
        padding: EdgeInsets.only(left: 15),
        height: 30,
        decoration: BoxDecoration(
            gradient: LinearGradient(
                //渐变位置
                begin: Alignment.topRight, //右上
                end: Alignment.bottomLeft, //左下
                stops: [
                  0.0,
                  1.0
                ], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: [
                  Color.fromRGBO(255, 134, 134, 1),
                  Color.fromRGBO(255, 36, 36, 1)
                ]),
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(leftRadius),
                topRight: Radius.circular(rightRadius),
                bottomLeft: Radius.circular(leftRadius),
                bottomRight: Radius.circular(rightRadius))),
        width: _getSingleItemWidth(count),
        child: Text(
          "$typeName($count)",
          style: TextStyle(fontSize: 16, color: Colors.white),
        ),
      ),
    );
  }

  _getSingleItemWidth(count) {
    var fenmu = 1;
    if (typeNumList != null && typeNumList.length > 0) {
      if (typeNumList[0].num > 0) {
        fenmu = typeNumList[0].num;
      }
    }
    double stableWidth = 100;
    double validBarWidth = MediaQuery.of(context).size.width -
        cardMargin * 2 -
        barItemMarginLeft -
        barItemMarginRight -
        stableWidth;
    singleBarWidth = validBarWidth / fenmu;
    print("singleBarWidth$singleBarWidth");
    return stableWidth + singleBarWidth * count;
  }

  getAlarmInfo() async {
    if (isRequesting == true) {
      return;
    }
    isRequesting = true;
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        HomeHttpUrl.HOME_ALARM_SUMMARY_INFO,
        params,
        NetListenerImpl((response) {
          isRequesting = false;
          setState(() {
            if (response != null && response.data != null) {
              ResHomeAlarmInfo res = ResHomeAlarmInfo.fromJson(response.data);
              if (res != null && res.data != null) {
                _homeAlarmInfoDetail = res.data;
                if (_homeAlarmInfoDetail != null) {
                  isLoading = false;
                  typeNumList = _homeAlarmInfoDetail.alarmTypeNum ?? [];
                  list = _homeAlarmInfoDetail.list ?? [];
                }
              }
            }
          });
        }, (errorRes) {
          isRequesting = false;
          setState(() {
            isLoading = false;
          });
        }));


  }

  getJobAlarmInfo() async {
    if (isRequesting == true) {
      return;
    }
    isRequesting = true;
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        HomeHttpUrl.HOME_ALARM_JOB_INFO,
        params,
        NetListenerImpl((response) {
          setState(() {
            isRequesting = false;
            if (response != null && response.data != null) {
              ResHomeAlarmInfo res = ResHomeAlarmInfo.fromJson(response.data);
              if (res != null && res.data != null) {
                _homeAlarmInfoDetail = res.data;
                if (_homeAlarmInfoDetail != null) {
                  isLoading = false;
                  typeNumList = _homeAlarmInfoDetail.alarmTypeNum ?? [];
                  list = _homeAlarmInfoDetail.list ?? [];
                }
              }
            }
          });
        }, (errorRes) {
          isRequesting = false;
          setState(() {
            isLoading = false;
          });
        }));
  }

  getVehicleAlarmInfo() async {
    if (isRequesting == true) {
      return;
    }
    isRequesting = true;
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        HomeHttpUrl.HOME_ALARM_VEHICLE_INFO,
        params,
        NetListenerImpl((response) {
          isRequesting = false;
          setState(() {
            if (response != null && response.data != null) {
              ResHomeAlarmInfo res = ResHomeAlarmInfo.fromJson(response.data);
              if (res != null && res.data != null) {
                _homeAlarmInfoDetail = res.data;
                if (_homeAlarmInfoDetail != null) {
                  isLoading = false;
                  typeNumList = _homeAlarmInfoDetail.alarmTypeNum ?? [];
                  list = _homeAlarmInfoDetail.list ?? [];
                }
              }
            }
          });
        }, (errorRes) {
          isRequesting = false;
          setState(() {
            isLoading = false;
          });
        }));
  }
  //app/alarm/areaAlarming 等接口没有status字段 增加一个接口查询
 /* getStatusInfo(String url) async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        url,
        params,
        NetListenerImpl((response) {
          setState(() {
            if (response != null && response.data != null) {
              list = (response.data['data'] as List).map((i) => ObjAlarmInfo.fromJson(i)).toList();
            }
          });
        }, (errorRes) {
          setState(() {
            isLoading = false;
          });
        }));
  }*/

  refresh() async {
    setState(() {
//      isLoading = true;
    });
    if(currentIndex == 0){
      await getAlarmInfo();
    }else if(currentIndex == 1){
      await getVehicleAlarmInfo();
    }else if(currentIndex == 2){
      await getJobAlarmInfo();
    }

  }
}
